<template>
  <div>
    <h3>裁判等级</h3>
    <div class="container">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row :gutter="20" type="flex" style="margin-bottom: 20px;">
            <el-col :span="5">
              <el-select v-model="searchForm.areaId" size="small" collapse-tags filterable clearable placeholder="选择区域" @change="areaChange">
                <el-option :label="item.name" :value="item.areaId" v-for="(item,index) in areaData" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-select v-model="searchForm.orgIdStr" size="small" multiple collapse-tags filterable clearable placeholder="选择组织机构">
                <el-option :label="item.name" :value="item.orgId" v-for="(item,index) in orgData" :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="selectOrgAll">全选</el-button>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-select v-model="searchForm.empTypeIdStr" size="small" multiple collapse-tags filterable clearable placeholder="选择工作类型">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_employee_type" :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="searchForm.empTypeIdStr=Object.keys(dict_employee_type)">全选</el-button>
            </el-col>
            <el-col :span="5">
              <el-select v-model="searchForm.refereeTypeId" size="small" collapse-tags filterable clearable placeholder="选择裁判等级">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_refereeType" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.sportId" size="small" collapse-tags filterable clearable placeholder="选择运动项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row :gutter="20" type="flex">
            <el-col :span="5" style="display: flex;">
              <el-button @click="exportEvent" size="small" type="primary" icon="el-icon-download">导出</el-button>
              <el-button @click="printEvent"  size="small" type="primary" icon="el-icon-printer">打印</el-button>
            </el-col>
            <el-col :span="6">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="right" unlink-panels style="width: 90%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="5" :offset="4" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit" style="margin: 0 10px;"> 搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @keyup="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="name" title="教练员" sortable></vxe-table-column>
        <vxe-table-column field="empType" title="工作类型(专职)" sortable></vxe-table-column>
        <vxe-table-column field="heightName" title="工作类型(兼职)" sortable></vxe-table-column>
        <vxe-table-column field="createDate" title="获得时间" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="refereeType" title="裁判等级" sortable></vxe-table-column>
        <vxe-table-column field="memo" title="备注" sortable></vxe-table-column>
        <vxe-table-column field="org" title="组织机构" sortable></vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
  </div>
</template>

<script>
  import { statistics_org4provence,statistics_area,empId2pId,sport_all,sport_item_all,emp_referee_rank,emp_referee_rank_select,genEmpType4statistics,area2coachId } from '@/api/statistics.js'
  import { employee_type,profession_type,employee_status,getWage_level,by_sportId } from '@/api/dict.js'
  export default {
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_org: {},
        areaData: [],
        dict_person: {},
        dict_employee_type: {},
        dict_profession_type: {},
        dict_employee_status: {},
        dict_getWage_level: {},
        dict_emp: {},
        dict_empId2orgId: {},
        dict_jempId2TypeId: {},
        dict_empId2TypeId: {},
        dict_pId2TypeId: {},
        dict_jpId2TypeId: {},
        dict_coach: {},
        dict_status: {1:'开通',2:'审核',3:'关闭'},
        dict_skillType: {
          1: "国际级运动健将",
          2: "运动健将",
          3: "一级运动员",
          4: "二级运动员",
          5: "三级运动员",
        },
        dict_refereeType: {
          1: "国家级裁判",
          2: "一级裁判员",
          3: "二级裁判员",
          4: "三级裁判员",
          5: "国际级裁判",
        },
        dict_sport: {},
        dict_sport_item: {},
        searchForm: {
          areaId: '',
          refereeTypeId: '',
          empTypeIdStr: [],
          orgIdStr: [],
          sportId: '',
          startDate: '',
          endDate: '',
        },
        orgData: [],
        sportItemData: {},
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getOrg4emp()
      })
    },
    methods: {
      searchSubmit() {
        let data = {}
        if(this.searchForm.empTypeIdStr.length!=0) data.empTypeIdStr = this.searchForm.empTypeIdStr.join(',')
        if(this.searchForm.orgIdStr.length!=0) data.orgIdStr = this.searchForm.orgIdStr.join(',')
        if(this.searchForm.professionTypeId) data.professionTypeId = this.searchForm.professionTypeId
        if(this.searchForm.refereeTypeId) data.refereeTypeId = this.searchForm.refereeTypeId
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if (this.doubleDate){
          data.startDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        emp_referee_rank_select(data).then(res=>{
          if(res.code === 200 && res.data.length!=0){
            this.init_data(res.data)
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          areaId: '',
          refereeTypeId: '',
          empTypeIdStr: [],
          orgIdStr: [],
          sportId: '',
          startDate: '',
          endDate: '',
        }
        this.doubleDate = ''
        this.getOrg4emp()
      },
      selectOrgAll() {
        this.searchForm.orgIdStr = []
        this.orgData.forEach(item=>{
          this.searchForm.orgIdStr.push(item.orgId)
        })
      },
      areaChange(val) {
        this.orgData = []
        this.searchForm.orgIdStr = ''
        statistics_org4provence({areaId:val}).then(res=>{
          this.orgData = res.data
        })
      },
      getOrg4emp() {
        emp_referee_rank().then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.init_data(res.data)
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      init_data(data) {
        data.forEach(item=>{
          item.name = this.dict_emp[item.empId]
          item.empType = this.dict_empId2TypeId[item.empId]
          item.heightName = this.dict_jempId2TypeId[item.empId]
          item.createDate = this.$moment(item.createDate).format('YYYY-MM-DD')=='Invalid date'?'':this.$moment(item.createDate).format('YYYY-MM-DD')
          item.sport = this.dict_sport[item.sportId]
          item.refereeType = this.dict_refereeType[item.refereeTypeId]
          item.org = this.dict_org[this.dict_empId2orgId[item.empId]]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          statistics_org4provence().then(res=>{
            this.orgData = res.data
            res.data.forEach(item=>{
              this.dict_org[item.orgId] = item.name
            })
          })
          statistics_area().then(res=>{
            this.areaData = res.data
          })
          empId2pId().then(res=>{
            res.data.forEach(item=>{
              this.dict_person[item.pid] = item.idNo
            })
          })
          employee_type().then(res=>{
            this.dict_employee_type = res
          })
          sport_all().then(res=>{
            res.data.forEach(item=>{
              this.dict_sport[item.sportId] = item.name
            })
          })
          area2coachId().then(res=>{
            res.data.forEach(item=>{
              this.dict_coach[item.coachId] = item.name
            })
          })
          genEmpType4statistics().then(res=>{
            var employees = res.data;
            var dict_empType = {
                1:'教练员',
                2:'文化教师',
                3:'科医人员',
                4:'行政管理',
            }
            for(var i=0;i<employees.length;i++) {
                var jempTypeName = '';
                if(employees[i].height.length>0){
                    var ids = employees[i].height.split(',');
                    for(var j=0;j<ids.length;j++) {
                        jempTypeName+=dict_empType[ids[j]]+','
                    }
                    jempTypeName = jempTypeName.substring(0,jempTypeName.length-1)
                    this.dict_jempId2TypeId[employees[i].empId] = jempTypeName
                    this.dict_jpId2TypeId[employees[i].pid] = jempTypeName
                }else{
                    this.dict_jempId2TypeId[employees[i].empId] = ''
                    this.dict_jpId2TypeId[employees[i].pid] = ''

                }

                if(employees[i].empTypeId){
                    this.dict_empId2TypeId[employees[i].empId] = dict_empType[employees[i].empTypeId]
                    this.dict_pId2TypeId[employees[i].pid] = dict_empType[employees[i].empTypeId]
                }else{
                    this.dict_empId2TypeId[employees[i].empId] = '';
                    this.dict_pId2TypeId[employees[i].pid] = '';

                }
                this.dict_empId2orgId[employees[i].empId] = employees[i].orgId
                this.dict_emp[res.data[i].empId] = res.data[i].name;
            }
            resolve()
          })
        })
      },
      exportEvent() {
        this.loading = true
        setTimeout(() => {
          this.$refs.XTable.exportData({
            filename: '裁判等级',
            isHeader: true,
            isFooter: true,
            data: this.defaultDataList
          })
          this.loading = false
        }, 100)
      },
      printEvent() {
        let topHtml = '<h2>裁判等级</h2>'
        let num = this.page.pageSize
        this.page.pageSize = this.defaultDataList.length
        this.findList()
        setTimeout(()=>{
          this.$refs.XTable.print({
              sheetName: '裁判等级',
              beforePrintMethod: ({content}) => {
                  return topHtml + content
              }
          })
          this.page.pageSize = num
          this.findList()
        },1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = new RegExp(filterName, 'gi')
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
        } else {
          this.dataList = this.defaultDataList
          this.findList()
        }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        this.page.pageSize = this.defaultDataList.length
        this.findList()
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultDataList.length
          this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
.container{
  padding: 10px;
  background-color: #FFFFFF;
}
</style>
